package com.jackeysun.util

import android.app.Activity
import android.content.Context
import android.graphics.Rect
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import kotlin.math.abs

/**
 *   Created by sunxunchao on 2021/11/17.
 */

/**
 * 强制显示 {@link #InputMethodManager.SHOW_FORCED}
 */
fun View.bindSoftInput() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    isFocusable = true
    isFocusableInTouchMode = true
    requestFocus()
    imm.showSoftInput(this, 0)
}

fun View.unbindSoftInput() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}

/**
 * 切换软键盘，如果显示则隐藏，如果隐藏则显示
 */
fun Context.toggleSoftInput(): Boolean {
    val imm = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    return if (imm.isActive) {
        imm.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0)//隐藏
        false
    } else {
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)//显示
        true
    }
}

fun Activity.forceHideSoftInput() {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(window.decorView.windowToken, 0)
}

/**
 * 监听键盘高度
 */
fun Activity.keyboardHeight(block: (height: Int, isShowing: Boolean) -> Unit) {
    var height = 0
    window.decorView.viewTreeObserver.addOnGlobalLayoutListener {
        val rect = Rect()
        window.decorView.getWindowVisibleDisplayFrame(rect)
        if (height == 0) {
            height = rect.bottom
        } else if (height != rect.bottom) {
            val offset = rect.bottom - height
            Log.d("keyboard", "偏移 == $offset")
            height = rect.bottom

            if (offset > 0) {//关闭键盘
                block(abs(offset), false)
            } else {
                block(abs(offset), true)
            }
        }
    }
}


fun Context.isKeyboardShow(): Boolean {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    return imm.isActive
}
